package cn.startom.sjdzpsdk;

import cn.startom.sjdzpsdk.models.NotifyResult;
import com.alibaba.fastjson.JSON;
import jodd.util.StringUtil;
import lombok.Data;

import java.util.LinkedHashMap;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * 对外提供的外部调用类
 * @author chenzhe
 */
@Data
public class ORTicketService {
    private final  IClient client;
    /**
     * 路票接口服务类
     * @param domain 接口地址
     * @param pid  合作id
     * @param secret 授权码
     */
    public ORTicketService(String domain,int pid,String secret){
        client=new DefaultClient(domain,pid,secret);
    }

    /**
     * 获取门票产品列表
     * @param request
     * @return
     */
    public ItemListResponse getItemList(ItemListRequest request){
        return client.execut(request,ItemListResponse.class);
    }
    /**
     * 查询订单
     * @param request
     * @return
     */
    public OrderListResponse getOrders(OrderListRequest request){
        return client.execut(request,OrderListResponse.class);
    }
    /**
     * 创建订单
     * @param request
     * @return
     */
    public CreateOrderResponse createOrder(CreateOrderRequest request){
        return client.execut(request,CreateOrderResponse.class);
    }
    /**
     * 退票
     * @param request
     * @return
     */
    public RefundOrderResponse refund(RefundOrderRequest request){
        return client.execut(request,RefundOrderResponse.class);
    }

    /**
     * 验证通知结果签名是否合法
     * @param params  参数键值对
     * @return
     */
    public String checkSign(Map<String,String> params){
        NotifyResult r=new NotifyResult();
        r.setSuccess(true);
        r.setMessage("成功");
        String inputSign=params.get("_sig");
        if(!StringUtil.isBlank(inputSign)) {
            params.remove("_sig");
            Map<String, Object> sorted;
            sorted = params.entrySet()
                    .stream()
                    .sorted(CommonUtil.comparatorByKeyAsc)
                    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                            LinkedHashMap::new));

            //加密
            String sign = this.client.buildSign(sorted);
            if (!sign.equals(inputSign)) {
                r.setSuccess(false);
                r.setMessage("签名不正确");
            }
        }else{
            r.setSuccess(false);
            r.setMessage("_sig参数缺失");
        }
        return JSON.toJSONString(r);
    }


}
